package fr.aprr.geoloc.client.view;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.client.resources.ThemeStyles;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.data.shared.IconProvider;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.TreeStore;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.info.Info;
import com.sencha.gxt.widget.core.client.menu.Menu;
import com.sencha.gxt.widget.core.client.menu.MenuItem;
import com.sencha.gxt.widget.core.client.toolbar.SeparatorToolItem;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
import com.sencha.gxt.widget.core.client.tree.Tree;
import com.sencha.gxt.widget.core.client.tree.Tree.CheckCascade;

import fr.aprr.geoloc.client.Resources;
import fr.aprr.geoloc.client.service.DtoServices;
import fr.aprr.geoloc.client.service.DtoServicesAsync;
import fr.aprr.geoloc.shared.dto.BaseDto;
import fr.aprr.geoloc.shared.dto.GpsDto;
import fr.aprr.geoloc.shared.dto.TypeVehiDto;

public class MainPanel implements IsWidget {

	private BorderLayoutContainer con;

	FlotChart flot;
	CanvasWidget canvas;

	private static int autoId = 0;

	private final DtoServicesAsync dtoService = GWT.create(DtoServices.class);
	
	class KeyProvider implements ModelKeyProvider<BaseDto> {
		public String getKey(BaseDto item) {
			return (item instanceof TypeVehiDto ? "f-" : "m-") + item.getId().toString();
		}
	}
	
	public Widget asWidget() {
		// TODO Auto-generated method stub

		if (con == null) {
			flot = new FlotChart();
			canvas = new CanvasWidget();

			// Main Panel
			con = new BorderLayoutContainer();
			// con.addStyleName("source");
			con.setHeight("850px");

			// Vehicule Panel
			BorderLayoutData datalayout = new BorderLayoutData();
			datalayout.setMargins(new Margins(5, 0, 5, 5));
			datalayout.setCollapsible(true);
			datalayout.setSplit(true);
			datalayout.setCollapseMini(true);
			datalayout.setCollapseHidden(true);
		
			

			ToolBar toolBarve = new ToolBar();
			TextButton clickSelect = new TextButton("Add");
			clickSelect.setIcon(Resources.IMAGES.menu_show());
			toolBarve.add(clickSelect);

			final VerticalLayoutContainer vehiculelLayout = new VerticalLayoutContainer();
			vehiculelLayout.add(toolBarve);
			vehiculelLayout.setWidth(600);
		

			ContentPanel vehiculePanel = new ContentPanel();
			vehiculePanel.getHeader().hide();
			vehiculePanel
					.getBody()
					.getStyle()
					.setProperty("borderTop",
							"1px solid " + ThemeStyles.get().borderColor());
			vehiculePanel.setWidget(vehiculelLayout);
			
			
			// Get Data Vehicules form Database 
			
			dtoService.getDataVehicule(new AsyncCallback<List<GpsDto>>() {

				public void onFailure(Throwable arg0) {
					// TODO Auto-generated method stub
					Info.display("Menu", "Get Menu Erreur");
				}

				public void onSuccess(List<GpsDto> listGpsDto) {
					// TODO Auto-generated method stub
					
					TypeVehiDto root = makeTypeVehi("Root");

					TypeVehiDto all = makeTypeVehi("All");
					
					List<BaseDto> children = new ArrayList<BaseDto>();
					
					children.add(all);
					
					root.setChildren(children);
					
					TypeVehiDto typeVH = makeTypeVehi("VH");
					TypeVehiDto typePatrouille = makeTypeVehi("Patrouille");
					TypeVehiDto typeAutre = makeTypeVehi("Autre");
					TypeVehiDto typeViab = makeTypeVehi("Viab");
					
					
					for (GpsDto gpsDto : listGpsDto) {
						
					if (gpsDto.getType().equals("Patrouille")) {
						typePatrouille.addChild(makeGpsDto(gpsDto.getIdvehicule().toString(), typePatrouille));
						
					}
					
					else if (gpsDto.getType().equals("autre")) {
						typeAutre.addChild(makeGpsDto(gpsDto.getIdvehicule().toString(), typeAutre));
						
					}
					
					else if (gpsDto.getType().equals("Viab")) {
						typeViab.addChild(makeGpsDto(gpsDto.getIdvehicule().toString(), typeViab));
						
					}
					
					else if (gpsDto.getType().equals("VH")) {
						typeVH.addChild(makeGpsDto(gpsDto.getIdvehicule().toString(), typeVH));
						
					}
				}
					
					all.addChild(typePatrouille);
					all.addChild(typeViab);
					all.addChild(typeVH);
					all.addChild(typeAutre);
					
					
					
					TreeStore<BaseDto> treeStore = new TreeStore<BaseDto>(new KeyProvider());
					
					TypeVehiDto typeVehi = root;
					
					for (BaseDto baseDto : typeVehi.getChildren()) {
						treeStore.add(baseDto);
						
						if (baseDto instanceof TypeVehiDto) {
							processFolder(treeStore, (TypeVehiDto)baseDto);
						}
					}

					
					final Tree<BaseDto, String> tree = new Tree<BaseDto, String>(treeStore, new ValueProvider<BaseDto, String>(){
					
									public String getValue(BaseDto object) {
										// TODO Auto-generated method stub
										return object.getName();
									}
					
									public void setValue(BaseDto object, String value) {
										// TODO Auto-generated method stub
										
									}
					
									public String getPath() {
										// TODO Auto-generated method stub
										return "name";
									}
									
								});
								
								  tree.setWidth(300);
							      
							      tree.setIconProvider(new IconProvider<BaseDto>() {
									public ImageResource getIcon(BaseDto model) {
										// TODO Auto-generated method stub
										if (model instanceof TypeVehiDto) {
											if (model.getName().equals("All")) {
												return Resources.IMAGES.aprr();
											}
											
											if (model.getName().equals("Patrouille")) {
												return Resources.IMAGES.ptruck();
											}
											
											if (model.getName().equals("VH")) {
												return Resources.IMAGES.vhicon();
											}
											
											if (model.getName().equals("Viab")) {
												return Resources.IMAGES.viab();
											}
											
											if (model.getName().equals("autre")) {
												return Resources.IMAGES.autre();
											}
											
										}
										if (model.getTypeVehicule().equals("Patrouille")) {
											return Resources.IMAGES.ptruck();
										}
										if (model.getTypeVehicule().equals("Viab")) {
											return Resources.IMAGES.viab();
										}
										
										if (model.getTypeVehicule().equals("autre")) {
											return Resources.IMAGES.autre();
										}
										
										if (model.getTypeVehicule().equals("VH")) {
											return Resources.IMAGES.vhicon();
										}
										else {
											return Resources.IMAGES.autre();
										}
									}
								});
							      
							      
							      tree.setCheckable(true);
							      tree.setCheckStyle(CheckCascade.TRI);
							      tree.setAutoLoad(true);
							      
							      
							      tree.setAutoExpand(true);
							      tree.setToolTip("Test tooltip");
							      vehiculelLayout.add(tree);
				}

			});

			
			// Right Panel

			// ToolBar
			ToolBar toolBar = new ToolBar();

			TextButton scrollerButton = new TextButton("Visualisation");
			Menu scrollMenu = new Menu();
			scrollMenu.setMaxHeight(200);
			scrollMenu.add(new MenuItem(" 2H "));
			scrollMenu.add(new MenuItem(" 4H "));
			scrollerButton.setMenu(scrollMenu);

			toolBar.add(scrollerButton);
			toolBar.add(new SeparatorToolItem());

			TextButton clickBt = new TextButton("Add");
			clickBt.setIcon(Resources.IMAGES.menu_show());
			toolBar.add(clickBt);

			VerticalLayoutContainer verticalLayout = new VerticalLayoutContainer();
			verticalLayout.add(toolBar);
			verticalLayout.add(flot, new VerticalLayoutData(1, 0, new Margins(
					10, 70, 0, 70)));
			verticalLayout.add(canvas, new VerticalLayoutData(1, 0,
					new Margins(10, 70, 0, 70)));

			ContentPanel leftPanel = new ContentPanel();
			leftPanel.getHeader().hide();
			leftPanel
					.getBody()
					.getStyle()
					.setProperty("borderTop",
							"1px solid " + ThemeStyles.get().borderColor());

			MarginData centerData = new MarginData();
			centerData.setMargins(new Margins(5, 5, 5, 5));

			leftPanel.setWidget(verticalLayout);

			// Add to main Panel
			con.setWestWidget(vehiculePanel, datalayout);
			con.setCenterWidget(leftPanel, centerData);
		}

		return con;
	}

	
	private static TypeVehiDto makeTypeVehi(String name) {
		TypeVehiDto theReturn = new TypeVehiDto(++autoId, name);
		theReturn.setChildren((List<BaseDto>) new ArrayList<BaseDto>());
		return theReturn;
	}

	private static GpsDto makeGpsDto(String name, TypeVehiDto type) {
		return makeGpsDto(name, type.getName());
	}

	private static GpsDto makeGpsDto(String name, String type) {
		return new GpsDto(++autoId, 2, name, type);
	}
	
	private void processFolder(TreeStore<BaseDto> store, TypeVehiDto folder) {
	    for (BaseDto child : folder.getChildren()) {
	      store.add(folder, child);
	      if (child instanceof TypeVehiDto) {
	        processFolder(store, (TypeVehiDto) child);
	      }
	    }
	  }
}
